<template>
  <div class="container">
    <div class="g-flx wraper">
      <!-- 左侧位置选项 -->
      <div>
        <el-row>
          <el-col :span="4">位置顺序：</el-col>
          <el-col :span="20">
            <el-button :class="{'active': customLocation === Number(item.customLocation)}" v-for="item in orderList" :key="item.customLocation" @click="searchPosition(item)" :disabled="edit">{{ item.interestCodeDesc }}</el-button>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="4">剩余天数：</el-col>
          <el-col :span="20" class="last-days">位置{{ customLocation }}可用天数 <span>{{ maxLength }}天</span></el-col>
        </el-row>

        <h4 style="font-size: 18px;">活动时间</h4>
        <el-card>
          <calendar v-model="time" :range="range" :disabledDays="disabledDays" :maxLength="maxLength" :checkedDate="checkedDate" ref="calendar">
            <template #footer>
              <p class="active-days">生效天数 <span>{{ chooseNum }}</span> 天</p>
              <p>活动时间：{{ startTime }} 至 {{ endTime }}</p>
            </template>
          </calendar>
        </el-card>
      </div>

      <!-- 右侧图片 -->
      <div class="g-flx right-wrap">
        <div>
          <p>APP效果演示</p>
          <img :src="`https://weber-imgs.oss-cn-beijing.aliyuncs.com/ty/merchant/position${customLocation}.gif`" alt="">
        </div>
        <div>
          <p>发放范围</p>
          <img src="https://weber-imgs.oss-cn-beijing.aliyuncs.com/ty/merchant/map.png" alt="">
        </div>
      </div>
    </div>

    <div class="btn-group">
      <el-button @click="$router.go(-1)">返回</el-button>
      <el-button @click="submit" type="primary">提交</el-button>
    </div>
  </div>
</template>
<script>
import calendar from '@/components/work/calendar'
import { dateLast, getChoosedDate, addOrder, queryOrderById, update } from '@/api/marketShop'
import { mapGetters } from 'vuex'
import dayjs from 'dayjs'

export default {
  name: 'setOrder',
  components: {
    calendar
  },
  data () {
    return {
      range: [], // 可用日期范围
      orderList: [], // 位置按钮
      disabledDays: [], // 不可选日期，需要转换为”月-日“
      maxLength: 0, // 可选日期最大值
      customLocation: 1, // 位置
      interestCodeName: '',
      chooseNum: 0, // 已选天数
      startTime: '', // 选择开始日期
      endTime: '', // 选择结束日期
      time: {
        startTime: '',
        endTime: ''
      },
      edit: false,
      checkedDate: [], // 设置已选中的日期
      activeId: null, // 活动ID
      editId: null, // 修改时的ID
      curOrderPosition: null, // 当前选中的位置
    }
  },
  computed: {
    ...mapGetters(['gasInfo'])
  },
  watch: {
    time: {
      deep: true,
      handler (val) {
        if (!val.startTime || !val.endTime) return
        this.chooseNum = Math.floor((val.endTime - val.startTime) / (24 * 3600 * 1000)) + 1
        const startTime = this.whetherChooseToday(val.startTime) ? dayjs() : dayjs(val.startTime)
        this.startTime = startTime.format('YYYY-MM-DD HH:mm:ss')
        this.endTime = dayjs(val.endTime).format('YYYY-MM-DD 23:59:59')
      }
    }
  },
  methods: {
    // 获取剩余天数
    async getDateList () {
      try {
        const {code, result} = await dateLast({ gasId: this.gasInfo.gasId })
        if (code !== 200) return
        this.checkedDate = []
        this.orderList = result
        // 查找当前是否有已选中按钮
        const order = this.orderList.find(item => item.interestCodeName === this.curOrderPosition)
        this.edit ? this.getOrderData() : this.chooseOrder(order || this.orderList[0])
      } catch (error) {
        console.log(error)
      }
    },
    // 选择某一位置，生成日历
    async chooseOrder ({ num, interestCodeName, customLocation }) {
      this.curOrderPosition = interestCodeName
      this.maxLength = this.edit ? num + this.chooseNum : num
      this.interestCodeName = interestCodeName
      this.customLocation = Number(customLocation)
      this.$refs.calendar.clearChooseList()
      this.chooseNum = 0
      this.startTime = ''
      this.endTime = ''
      // 查询日期
      await this.getDate()
      this.$refs.calendar.initCalendar()
    },
    // 查询日期
    async getDate () {
      const params = {
        gasId: this.gasInfo.gasId,
        interestCodeName: this.interestCodeName,
        configId: this.edit ? this.editId : null
      }
      try {
        const {code, result: { days, disabledDays }} = await getChoosedDate(params)
        if (code !== 200) return
        // 如果是新增，默认自动选中第一个可选日期
        // if (!this.edit && usableDays.length) {
        //   this.checkedDate = [usableDays[0], usableDays[0]]
        //   this.startTime = dayjs(usableDays[0]).format('YYYY-MM-DD HH:mm:ss')
        //   this.endTime = dayjs(usableDays[0]).format('YYYY-MM-DD 23:59:59')
        //   this.time = {
        //     startTime: dayjs(this.startTime).valueOf(),
        //     endTime: dayjs(this.endTime).valueOf()
        //   }
        // }
        this.range[0] = new Date(+new Date())
        this.range[1] = new Date(+new Date() + (days - 1) * 24 * 3600 * 1000)
        this.disabledDays = disabledDays.map(item => dayjs(item).format('MM-DD'))
      } catch (error) {
        console.log(error)
      }
    },
    // 点击按钮
    searchPosition (item) {
      this.curOrderPosition = item.interestCodeName
      this.getDateList()
    },
    async submit () {
      if (!this.time.startTime || !this.time.endTime) {
        this.$message({
          message: '请选择活动时间',
          type: 'error'
        })
        return
      }
      this.edit ? this.editHttp() : this.addHttp()
    },
    // 调用新增接口
    async addHttp () {
      try {
        const {code, message} = await addOrder({
          gasId: this.gasInfo.gasId,
          interestCodeName: this.interestCodeName,
          startTime: this.whetherChooseToday(this.time.startTime) ? dayjs().valueOf() : this.time.startTime,
          endTime: this.time.endTime
        })
        if (code === 202) {
          this.$message({
            message,
            type: 'error'
          })
          this.getDateList()
        }
        if (code !== 200) return
        this.$message({
          message: '配置成功',
          type: 'success'
        })
        this.$router.push({ path: '/marketCenter/orderSuccess' })
      } catch (error) {
        console.log(error)
      }
    },
    // 修改接口
    async editHttp () {
      try {
        const {code, message} = await update({
          configId: this.editId,
          interestCodeName: this.interestCodeName,
          gasId: this.gasInfo.gasId,
          startTime: this.whetherChooseToday(this.time.startTime) ? dayjs().valueOf() : this.time.startTime,
          endTime: this.time.endTime
        })
        if (code === 202) {
          this.$message({
            message,
            type: 'error'
          })
          this.getDateList()
        }
        if (code !== 200) return
        this.$message({
          message: '配置成功',
          type: 'success'
        })
        this.$router.push({ path: '/marketCenter/orderSuccess' })
      } catch (error) {
        console.log(error)
      }
    },
    // 获取反显数据
    async getOrderData () {
      try {
        const { code, result: { interestCodeName, startTime, endTime, id } } = await queryOrderById({configId: this.activeId, gasId: this.gasInfo.gasId})
        if (code !== 200) return
        this.editId = id
        const order = this.orderList.find(item => item.interestCodeName === interestCodeName)
        this.chooseNum = Math.floor((endTime - startTime) / (24 * 3600 * 1000) + 1)
        await this.chooseOrder(order)
        this.time = {
          startTime: startTime,
          endTime: endTime
        }
        this.startTime = dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')
        this.endTime = dayjs(endTime).format('YYYY-MM-DD 23:59:59')
        this.checkedDate = [new Date(startTime), new Date(endTime)]
        this.$nextTick(() => {
          this.$refs.calendar.initCalendar()
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 检查是否选择了当前日期
    whetherChooseToday (time) {
      return dayjs(time).format('YYYY-MM-DD') === dayjs().format('YYYY-MM-DD')
    }
  },
  created () {
    if (this.$route.query.activeId) {
      this.activeId = this.$route.query.activeId
      this.edit = true
    }
    this.getDateList()
  }
}
</script>
<style lang="less" scoped>
  .container {
    width: 100%;
    font-size: 14px;
    color: #333333;
    background: #fff;
    margin: 10px;
    padding: 24px 20px;
    .wraper {
      &>div{
        width: 50%;
        .el-row {
          color: #333333;
          height: 60px;
          line-height: 60px;
          .last-days {
            color: #333333;
            font-weight: 600;
            span {
              color: #4B7EFE;
            }
          }
        }
      }
      .active-days {
        margin-top: 30px;
        font-size: 18px;
        font-weight: 600;
        color: #333333;
        span {
          font-size: 24px;
          color: #4B7EFE;
        }
        &+p {
          color: #999999;
        }
      }
      .el-button {
        width: 110px;
        height: 30px;
        line-height: 30px;
        padding: 0;
        border: 1px solid #4765F9;
        color: #4765F9;
        background: rgba(71, 101, 249, 0.09);
      }
      .active {
        background: #4B7EFE;
        color: #fff;
        border-radius: 4px;
      }
    }
    .right-wrap {
      p {
        font-size: 18px;
        font-weight: 600;
        color: #222222;
        margin-left: 10%;
      }
      &>div {
        width: 50%;
      }
      img {
        width: 90%;
        margin-left: 5%;
      }
    }
    .btn-group {
      margin-top: 30px;
      /deep/.el-button {
        width: 125px;
      }
    }
  }
</style>